package com.my.demo.book;

import java.util.ArrayList;
import java.util.Iterator;

import Ice.AsyncResult;

public class MyClient {
	public static void main(String[] args) {
//		callServer(args);
		callAsynServer(args);
	}
	
	public static void callServer(String[] args){
		int status = 0;
		Ice.Communicator ic = null;
		try{
			//初始化通信器
			ic = Ice.Util.initialize(args);
			
			//传入远程服务单元的名称、网络协议、IP及端口，构造一个Proxy对象
			Ice.ObjectPrx base = ic.stringToProxy("OnlineBook:default -p 10000");
			
			//通过checkedCast向下转型，获取OnlineBook接口的远程代理，并同时检测根据传入的名称
			//获取服务单元是否onlineBook的代理接口
			OnlineBookPrx proxy = OnlineBookPrxHelper.checkedCast(base);
			if(proxy == null){
				throw new Error("Invalid proxy");
			}
			
			//调用服务方法
			Message m = proxy.bookTick(new Message("m1", 1, 2));
			System.out.println(m.type);
		}catch (Exception e) {
			e.printStackTrace();
			status = 1;
		}finally{
			if(ic != null){
				ic.destroy();
			}
		}
		System.exit(status);
	}
	
	public static void callAsynServer(String[] args){
		int status = 0;
		Ice.Communicator ic = null;
		try{
			//初始化通信器
			ic = Ice.Util.initialize(args);
			
			//传入远程服务单元的名称、网络协议、IP及端口，构造一个Proxy对象
			Ice.ObjectPrx base = ic.stringToProxy("OnlineBook:default -p 10000");
			
			//通过checkedCast向下转型，获取OnlineBook接口的远程代理，并同时检测根据传入的名称
			//获取服务单元是否onlineBook的代理接口
			OnlineBookPrx proxy = OnlineBookPrxHelper.checkedCast(base);
			if(proxy == null){
				throw new Error("Invalid proxy");
			}
			
			//异步调用服务方法
			ArrayList<AsyncResult> asyRstLst = new ArrayList<AsyncResult>();
			for(int i = 0; i < 100; i++){
				asyRstLst.add(proxy.begin_bookTick(new Message("M" + i, 1, i)));
			}
			
			System.out.println("begin end.");
			
			while(!asyRstLst.isEmpty()){
				Iterator<AsyncResult> it = asyRstLst.iterator();
				while(it.hasNext()){
					AsyncResult curResult = it.next();
					if(curResult.isCompleted()){
						Message curMessage = proxy.end_bookTick(curResult);
						System.out.println(String.format("[%s,%4d,%4.0f]", curMessage.name, curMessage.type, curMessage.price));
						it.remove();
					}
				}
				Thread.sleep(100);
			}
		}catch (Exception e) {
			e.printStackTrace();
			status = 1;
		}finally{
			if(ic != null){
				ic.destroy();
			}
		}
		System.exit(status);
	}
}
